<?php

/**
 * Manage gescom ajax like
 *
 * @package gescom
 * @author Rémi Peron
 **/
class GescomController extends GescomAppController
{
	var $name = 'Gescom';
	var $helpers = array('Html', 'Form', 'Javascript', 'Ajax');
	var $components = array('UserAuth', 'RequestHandler');
//	var $uses = array('Project', 'Batch');
	var $url_receiptbook_service = "http://www.jeuxcherche.net/gescom_receiptbook.php";
	var $url_ticket_service = "http://www.jeuxcherche.net/gescom_ticket.php";

	function beforeFilter( ) {
	    if ($this->RequestHandler->isAjax()) {
	        $db =& ConnectionManager::getDataSource('default');
	        $db->fullDebug = false;
	    }
		$this->set('project_id', 0);
		$this->set('project_name', '');
	}

	function index() {
		
	}
	
	function add() {
		$this->render('add', 'ajax');
	}
	
	function cancel() {
		$this->render('cancel', 'ajax');
	}

	/**
	 * Synchronize receiptbooks with Gescom services
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	public function synchronize_receiptbook()
	{
		$results = $this->Gescom->query("SELECT * FROM `receiptbooks`, gescoms 
										  WHERE `status` = 'opened' 
										  AND receiptbooks.project_id = gescoms.project_id");
		foreach ($results as $result)
		{
			$url = $this->url_receiptbook_service.'?code_projet='.$result['gescoms']['code_client'].'&code_affaire='.$result['gescoms']['code_affaire'];
			$xml = simplexml_load_file($url);
			$new_amount = $xml->receiptbook->amount;
			if ($new_amount != $result['receiptbooks']['amount'])
				$this->Gescom->query("UPDATE `receiptbooks`
										  SET `amount` = '".$new_amount."' 
										WHERE `id` = '".$result['receiptbooks']['id']."'");
		}
		exit();
	}
	
	/**
	 * Synchronize tickets with Gescom services
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	public function synchronize_closed_tickets()
	{
		$results = $this->Gescom->query("SELECT * FROM tickets, gescoms 
										  WHERE `status` = 'closed' AND gescom = 0
										  AND tickets.project_id = gescoms.project_id");
		foreach ($results as $result)
		{
			$url = $this->url_ticket_service.'?code_projet='.$result['gescoms']['code_client'].'&code_affaire='
											.$result['gescoms']['code_affaire'].'&ticket_id='
											.$result['tickets']['id'];
			$xml = simplexml_load_file($url);
			$gescom_amount = $xml->ticket->amount;
			$webx_amount = 0;
			$results2 = $this->Gescom->query("SELECT * FROM fundings WHERE `ticket_id` = '".$result['tickets']['id']."'");
			foreach ($results2 as $result2) {
				$webx_amount += $result2['fundings']['amount'];
			}
			if ($webx_amount == $gescom_amount)
				$this->Gescom->query("UPDATE tickets SET gescom = '1' WHERE id = '".$result['tickets']['id']."'");
		}
		exit();
	}

} // END class GescomManageController extends GescomAppController

?>
